package mq.rabbitmq.confirm;

import com.rabbitmq.client.*;
import mq.rabbitmq.RabbitMqChannelFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static mq.rabbitmq.Constant.CONFIRM_EX_CHANGE;
import static mq.rabbitmq.Constant.CONFIRM_ROUTING_KEY;

/**
 * 消费者
 *
 * @author verlet
 * @date 2019/9/11
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 声明channel
        Channel channel = RabbitMqChannelFactory.createChannel();
        channel.exchangeDeclare(CONFIRM_EX_CHANGE, BuiltinExchangeType.TOPIC, false, false, null);
        // 声明一个队列
        String queueName = "confirmQueue";
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, CONFIRM_EX_CHANGE, CONFIRM_ROUTING_KEY);
        // 创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                System.out.println("-------------自定义消费者------------");
                System.out.println("consumerTag : " + consumerTag);
                System.out.println("envelope : " + envelope);
                System.out.println("properties : " + properties);
                System.out.println("body : " + new String(body));
            }

        };
        // 设置channel 为自定义消费者
        channel.basicConsume(queueName, true, consumer);
        Thread.sleep(1000);
        // 关闭连接
        RabbitMqChannelFactory.close(channel);
    }
}
